package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.MyTheadLocal;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Component
@Order(1)
public class MyFilter implements Filter {
    @Value("${nologin.url}")
    private String url;

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException,
            ServletException, IOException {


        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String requestURI = httpServletRequest.getRequestURI();

        AntPathMatcher antPathMatcher = new AntPathMatcher();

        String[] patterns = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        Long shuju = (Long) httpServletRequest.getSession().getAttribute("shuju");

        User loginPhone = (User) httpServletRequest.getSession().getAttribute("loginPhone");

        for (String pattern : patterns) {
            boolean match = antPathMatcher.match(pattern, requestURI);

            if (match){

                chain.doFilter(request,response);

                return;
            }

        //登陆成功
        if (shuju != null){
            MyTheadLocal.set(shuju);
            chain.doFilter(request,response);
            MyTheadLocal.remove();
            return;
        }


            if (loginPhone != null){

                MyTheadLocal.set(loginPhone.getId());

                chain.doFilter(request,response);

                MyTheadLocal.remove();
                return;
            }




        }




        R<Object> notlogin = R.error("NOTLOGIN");

        String s = JSON.toJSONString(notlogin);

        response.getWriter().write(s);


    }
}
